package cn.zy.basic.controller;

import cn.zy.basic.util.AjaxResult;
import cn.zy.basic.util.FastDfsUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 上传 - 需要【请求方式：post】
 * 下载 - 不需要
 * 删除 - 需要【请求方式：delete】
 * 修改 - 不需要 = 先删除再上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传接口
     * @param file 于elementUi的上传组件中name属性值一致
     * @return
     * post：http://localhost:8080/fastDfs
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){
        try {
            String oName = file.getOriginalFilename(); //xx.png
            String exeName = oName.substring(oName.lastIndexOf(".") + 1);//png
            //调用工具类
            String fileName = FastDfsUtils.upload(file.getBytes(), exeName);
            return AjaxResult.me().setObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }
    }

    /**
     * 删除接口
     * @return
     * delete http://localhost:8080/fastDfs/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     * 后端接收：@PathV("/{a}/{b}/{c}/{d}") - 麻烦
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam("path")String path){
        try {
            //path = /group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            path = path.substring(1); //   group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            String groupName = path.substring(0,path.indexOf("/")); // group1
            String fileName = path.substring(path.indexOf("/")+1);// M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
